package com.zhi.syc.data_applist.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Build;
import android.telephony.CellInfo;
import android.telephony.CellInfoCdma;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.CellSignalStrengthCdma;
import android.telephony.CellSignalStrengthGsm;
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellSignalStrengthWcdma;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Size;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class ASHarewareUtil {

    public static String getSensorList(Context context) {
        JSONArray jsonArray = new JSONArray();
        String sensorStr = "";
        try {
            SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
            List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
            for (int i = 0; i < sensors.size(); i++) {
                Sensor sensor = sensors.get(i);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", sensor.getType() + "");
                jsonObject.put("name", ASUtil.safeString(sensor.getName()));
                jsonObject.put("version", sensor.getVersion() + "");
                jsonObject.put("maxRange", ASUtil.safeString(String.valueOf(sensor.getMaximumRange())));
                jsonObject.put("vendor", ASUtil.safeString(sensor.getVendor()));
                jsonObject.put("minDelay", ASUtil.safeString(String.valueOf(sensor.getMinDelay())));
                jsonObject.put("power", ASUtil.safeString(String.valueOf(sensor.getPower())));
                jsonObject.put("resolution", ASUtil.safeString(String.valueOf(sensor.getResolution())));
                jsonArray.put(jsonObject);
            }
            sensors = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        sensorStr = jsonArray.toString();
        jsonArray = null;
        return sensorStr;
    }

    public static String getIsRoot(Context context) {
        String root = "NO";
        String binPath = "/system/bin/su";
        String xBinPath = "/system/xbin/su";
        try {
            if (new File(binPath).exists() && isExecutable(binPath)) {
                root = "YES";
            }
            if (new File(xBinPath).exists() && isExecutable(xBinPath)) {
                root = "YES";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return root;
    }

    public static boolean isExecutable(String filePath) {
        Process p = null;
        try {
            p = Runtime.getRuntime().exec("ls -l " + filePath);
            // 获取返回内容
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str = in.readLine();
            if (str != null && str.length() >= 4) {
                char flag = str.charAt(3);
                if (flag == 's' || flag == 'x')
                    return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (p != null) {
                p.destroy();
            }
        }
        return false;
    }

    public static String getKeyboard(Context context) {
        String keyboard = "";

//        int KEYBOARD_UNDEFINED = 0; // 未定义的键盘
//        int KEYBOARD_NOKEYS = 1; // 无键键盘，没有外接键盘时为该类型
//        int KEYBOARD_QWERTY = 2; // 标准外接键盘
//        int KEYBOARD_12KEY = 3; // 12键小键盘

        try {
            Configuration config = context.getResources().getConfiguration();
            keyboard = ASUtil.safeString(String.valueOf(config.keyboard));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return keyboard;
    }

    public static String getIsSimulator(Context context) {
        String isSim = "NO";
        if (notHasLightSensorManager(context) ||
                isFeatures() ||
                checkIsNotRealPhone() ||
                checkPipes()) {
            isSim = "YES";
        }
        return isSim;
    }

    public static Boolean notHasLightSensorManager(Context context) {
        try {
            SensorManager sensorManager = (SensorManager) context.getSystemService(context.SENSOR_SERVICE);
            Sensor sensor8 = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); //光
            if (null == sensor8) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isFeatures() {
        return Build.FINGERPRINT.startsWith("generic")
                || Build.FINGERPRINT.toLowerCase().contains("vbox")
                || Build.FINGERPRINT.toLowerCase().contains("test-keys")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDK built for x86")
                || Build.MANUFACTURER.contains("Genymotion")
                || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                || "google_sdk".equals(Build.PRODUCT);
    }

    public static boolean checkIsNotRealPhone() {
        String cpuInfo = readCpuInfo();
        if ((cpuInfo.contains("intel") || cpuInfo.contains("amd"))) {
            return true;
        }
        return false;
    }

    public static String readCpuInfo() {
        String result = "";
        try {
            String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
            ProcessBuilder cmd = new ProcessBuilder(args);

            Process process = cmd.start();
            StringBuffer sb = new StringBuffer();
            String readLine = "";
            String mUtf8Char = "UTF-8";
            BufferedReader responseReader = new BufferedReader(new InputStreamReader(process.getInputStream(), mUtf8Char));
            while ((readLine = responseReader.readLine()) != null) {
                sb.append(readLine);
            }
            responseReader.close();
            result = sb.toString().toLowerCase();
        } catch (IOException ex) {
        }
        return result;
    }

    private static String[] known_pipes = {"/dev/socket/qemud", "/dev/qemu_pipe"};

    public static boolean checkPipes() {
        try {
            for (int i = 0; i < known_pipes.length; i++) {
                String pipes = known_pipes[i];
                File qemu_socket = new File(pipes);
                if (qemu_socket.exists()) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getMobileDbm(Context context) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return "";
        }

        String dbmStr = "";
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                List<CellInfo> cellInfoList = tm.getAllCellInfo();
                if (null != cellInfoList) {
                    for (CellInfo cellInfo : cellInfoList) {
                        if (cellInfo instanceof CellInfoGsm) {
                            CellSignalStrengthGsm cellSignalStrengthGsm = ((CellInfoGsm) cellInfo).getCellSignalStrength();
                            int dbm = cellSignalStrengthGsm.getDbm();
                            dbmStr = ASUtil.safeString(String.valueOf(dbm));
                        } else if (cellInfo instanceof CellInfoCdma) {
                            CellSignalStrengthCdma cellSignalStrengthCdma = ((CellInfoCdma) cellInfo).getCellSignalStrength();
                            int dbm = cellSignalStrengthCdma.getDbm();
                            dbmStr = ASUtil.safeString(String.valueOf(dbm));
                        } else if (cellInfo instanceof CellInfoWcdma) {
                            CellSignalStrengthWcdma cellSignalStrengthWcdma = ((CellInfoWcdma) cellInfo).getCellSignalStrength();
                            int dbm = cellSignalStrengthWcdma.getDbm();
                            dbmStr = ASUtil.safeString(String.valueOf(dbm));
                        } else if (cellInfo instanceof CellInfoLte) {
                            CellSignalStrengthLte cellSignalStrengthLte = ((CellInfoLte) cellInfo).getCellSignalStrength();
                            int dbm = cellSignalStrengthLte.getDbm();
                            dbmStr = ASUtil.safeString(String.valueOf(dbm));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //ASLogger.d("getMobileDbm", dbmStr);
        return dbmStr;
    }

    public static String getFrontCameraPixels(Context paramContext) {
        int camerId = hasFrontCamera(paramContext);
        return getCameraPixels(paramContext, camerId);
    }

    public static String getBackCameraPixels(Context paramContext) {
        int camerId = hasBackCamera(paramContext);
        return getCameraPixels(paramContext, camerId);
    }

    public static int hasFrontCamera(Context paramContext) {
        int CAMERA_FACING_FRONT = 1;
        int cid = -1;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CameraManager cameraManager = (CameraManager) paramContext.getSystemService(Context.CAMERA_SERVICE);
            String[] cameraIds = {};
            try {
                cameraIds = cameraManager.getCameraIdList();
                for (int i = 0; i < cameraIds.length; i++) {
                    String cID = cameraIds[i];
                    if (cID.equalsIgnoreCase(CameraCharacteristics.LENS_FACING_BACK + "")) {
                        cid = Integer.parseInt(cID);
                        break;
                    }
                }
            } catch (@SuppressLint("NewApi") CameraAccessException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            cameraIds = null;
        } else {
            try {
                int numberOfCameras = android.hardware.Camera.getNumberOfCameras();
                android.hardware.Camera.CameraInfo cameraInfo = new android.hardware.Camera.CameraInfo();
                for (int i = 0; i < numberOfCameras; i++) {
                    android.hardware.Camera.getCameraInfo(i, cameraInfo);
                    if (cameraInfo.facing == CAMERA_FACING_FRONT) {
                        cid = i;
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return cid;
    }

    public static int hasBackCamera(Context paramContext) {
        int CAMERA_FACING_BACK = 0;
        int cid = -1;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                CameraManager cameraManager = (CameraManager) paramContext.getSystemService(Context.CAMERA_SERVICE);
                String[] cameraIds = cameraManager.getCameraIdList();
                for (int i = 0; i < cameraIds.length; i++) {
                    String cID = cameraIds[i];
                    if (cID.equalsIgnoreCase(CameraCharacteristics.LENS_FACING_FRONT + "")) {
                        cid = Integer.parseInt(cID);
                        break;
                    }
                }
                cameraIds = null;
            } catch (@SuppressLint("NewApi") CameraAccessException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                int numberOfCameras = android.hardware.Camera.getNumberOfCameras();
                android.hardware.Camera.CameraInfo cameraInfo = new android.hardware.Camera.CameraInfo();
                for (int i = 0; i < numberOfCameras; i++) {
                    android.hardware.Camera.getCameraInfo(i, cameraInfo);
                    if (cameraInfo.facing == CAMERA_FACING_BACK) {
                        cid = i;
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return cid;
    }

    public static String getCameraPixels(Context paramContext, int paramInt) {
        String pixelValue = "0";
        if (paramInt == -1)
            return pixelValue;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                Camera mcamera = Camera.open(paramInt);
                if (mcamera == null) {
                    return pixelValue;
                }
                Camera.Parameters parameters = mcamera.getParameters();
                if (parameters == null) {
                    return pixelValue;
                }
                List<int[]> SupPreFpsRangeList = parameters.getSupportedPreviewFpsRange();
                if (SupPreFpsRangeList == null || SupPreFpsRangeList.size() == 0) {
                    return pixelValue;
                }

                CameraManager cameraManager = (CameraManager) paramContext.getSystemService(Context.CAMERA_SERVICE);
                CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(paramInt + "");
                StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                Size[] sizes = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);
                if (sizes.length > 0) {
                    Size fistSize = sizes[0];
                    int gwidth = fistSize.getWidth();
                    int gheight = fistSize.getHeight();
                    int pixels = (gwidth * gheight / 10000);
                    pixelValue = (pixels + "");
                }
                sizes = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                android.hardware.Camera localCamera = android.hardware.Camera.open(paramInt);
                android.hardware.Camera.Parameters localParameters = localCamera.getParameters();
                localParameters.set("camera-id", 1);
                List<Camera.Size> localList = localParameters.getSupportedPictureSizes();
                if (localList != null) {
                    int heights[] = new int[localList.size()];
                    int widths[] = new int[localList.size()];
                    for (int i = 0; i < localList.size(); i++) {
                        Camera.Size size = (Camera.Size) localList.get(i);
                        int sizehieght = size.height;
                        int sizewidth = size.width;
                        heights[i] = sizehieght;
                        widths[i] = sizewidth;
                    }
                    int pixels = getMaxNumber(heights) * getMaxNumber(widths);
                    localCamera.release();
                    pixelValue = String.valueOf((pixels / 10000));

                    localList.clear();
                    localList = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return pixelValue;
    }

    public static int getMaxNumber(int[] paramArray) {
        int temp = 0;
        try {
            if (paramArray.length > 0) {
                temp = paramArray[0];
                for (int i = 0; i < paramArray.length; i++) {
                    if (temp < paramArray[i]) {
                        temp = paramArray[i];
                    }
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static String getPhySicalSize(Context paramContext) {
        String sizeStr = "";
        try {
            Point point = new Point();
            WindowManager wm = (WindowManager) paramContext.getSystemService(Context.WINDOW_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                wm.getDefaultDisplay().getRealSize(point);
            }
            DisplayMetrics dm = paramContext.getResources().getDisplayMetrics();
            double x = Math.pow(point.x / dm.xdpi, 2);
            double y = Math.pow(point.y / dm.ydpi, 2);
            double screenInches = Math.sqrt(x + y);
            sizeStr = String.valueOf(screenInches);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sizeStr;
    }
}
